package com.gisquest.cloud.common.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @Author guowei
 * @Date 2020/6/23 18:58
 * @Description:
 **/
@Configuration
@EnableCaching
public class RedisCacheConfiguration {

  Logger logger = LoggerFactory.getLogger(RedisCacheConfiguration.class);
  @Value("${redis.host}")
  private String host;
  @Value("${redis.pool.max-idle}")
  private int maxIdle;
  @Value("${redis.pool.max-wait}")
  private long maxWaitMillis;
  @Value("${redis.password}")
  private String password;
  @Value("${redis.port}")
  private int port;
  @Value("${redis.timeout}")
  private int timeout;

  @Bean
  public static PropertySourcesPlaceholderConfigurer properties() {
    PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
    YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
    yaml.setResources(new ClassPathResource[0]);

    pspc.setProperties(yaml.getObject());
    return pspc;
  }

  @Bean
  public JedisPool redisPoolFactory() {
    this.logger.info("redis地址：" + this.host + ":" + this.port);
    JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
    jedisPoolConfig.setMaxIdle(this.maxIdle);
    jedisPoolConfig.setMaxWaitMillis(this.maxWaitMillis);
    JedisPool jedisPool;
    if (StringUtils.isEmpty(this.password)){
      jedisPool = new JedisPool(jedisPoolConfig, this.host, this.port, this.timeout);
    } else {
      jedisPool = new JedisPool(jedisPoolConfig, this.host, this.port, this.timeout, this.password);
    }
    return jedisPool;
  }

}
